/*
 *    This file is part of CeluMap.
 *
 *    CeluMap is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    CeluMap is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Copyright 2006, 2007, 2008 Gonzalo Merayo
 *    gonzalo (at) celumap.com.ar
 *    www.celumap.com.ar
 *
 */

package map.file;

import map.Map;
import figures.Figure;
import figures.FigureIterator;
import geometry.Rectangle;

public class CombinationMap implements Map, FigureIterator {
	
	protected Map[] cuadrantes = null;
	private Rectangle area = null;
	FigureIterator[] figsIterators;
	int iterator = 0;
		
	public void appendMap(Map map) {
		if(cuadrantes == null){
			cuadrantes = new Map[1];
		}else{
			Map[] tmp = new Map[cuadrantes.length+1];
			figsIterators = new FigureIterator[cuadrantes.length+1];
			for(int i=0;i<cuadrantes.length;i++)
				tmp[i] = cuadrantes[i];
			cuadrantes = tmp;
		}
		cuadrantes[cuadrantes.length-1] = map;
	}
	
	public FigureIterator getFigures(Rectangle area) {
		if(this.area!=null && !this.area.colides(area)){
			for(int i=0; i<cuadrantes.length; i++)
				cuadrantes[i].getFigures(area);
			return null;
		}
		int f = 0;
		if(cuadrantes == null)
			return null;
		for(int i=0; i<cuadrantes.length; i++){
			figsIterators[f] = cuadrantes[i].getFigures(area);
			if(figsIterators[f]!=null)
				f++;
		}
		for(; f<cuadrantes.length; f++)
			figsIterators[f]=null;
		iterator = 0;
		return this;
	}
	
	public boolean hasNext() {
		if(iterator == figsIterators.length)
			return false;//end of iterators
		if(figsIterators[iterator] == null)
			return false;
		if(figsIterators[iterator].hasNext())
			return true;
		iterator++;
		return hasNext();//this checks if the next iterator is empty
	}

	public Figure next() {
		return figsIterators[iterator].next();
	}	
	
	public Rectangle getArea(){
		return area;
	}
	
	public void setArea(Rectangle r){
		area = r;
	}
}
